package com.jp.knowledge.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.comm.InfoDetailData;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.InfoTopicAdapter;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.http.ToutiaoGetDataUtil;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.TopicInfo;
import com.jp.knowledge.model.TopicListInfo;
import com.jp.knowledge.util.ImageLoadUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.TalkBottomBarView;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;


public class InfoTopicActivity extends SlidingActivity implements View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, TalkBottomBarView.TalkBottomBarCallback, ToutiaoGetDataUtil.GetDataCallback, ResultSubscriber.OnResultListener {

    private static final int TOPIC_DELETE_CODE = 0x01;

    private InfoDetailData infoDetailData;
    private ToutiaoGetDataUtil getDataUtil;
    private boolean hasTopicData;

    private BroadcastReceiver weChatBroadcaseReciver;
    private LocalBroadcastManager weChatLocalBroadcastManager;

    @ViewInject(R.id.topic_remind_view)
    private LinearLayout topicRemindView;
    @ViewInject(R.id.topic_data_view)
    private LinearLayout topicDataView;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout topicRefreshView;
    @ViewInject(R.id.topic_count)
    private TextView topicCount;
    @ViewInject(R.id.topic_head)
    private ImageView topicHead;
    @ViewInject(R.id.topic_name)
    private TextView topicName;
    @ViewInject(R.id.topic_content)
    private TextView topicContent;
    @ViewInject(R.id.topic_praise_num)
    private TextView topicPraiseNum;
    @ViewInject(R.id.topic_reward_num)
    private TextView topicRewardNum;
    @ViewInject(R.id.topic_delete)
    private TextView topicDelete;
    @ViewInject(R.id.can_content_view)
    private RecyclerView topicOtherRv;
    @ViewInject(R.id.topic_bottom_talk_bar)
    private TalkBottomBarView topicBottomTalkBar;

    private CommDialog deleteDialog;
    private InfoTopicAdapter infoTopicAdapter;

    @Override
    protected int getResourceId() {
        return R.layout.activity_info_topic;
    }

    @Override
    protected void init() {
        infoDetailData = InfoDetailData.getInfoDetail();
        getDataUtil = new ToutiaoGetDataUtil(this);
        getDataUtil.setGetDataCallback(this);
        String uuid = application.getUserData() == null ? null : application.getUserData().getUuid();
        infoTopicAdapter = new InfoTopicAdapter(this, new ArrayList<TopicListInfo>(), uuid);

        initView();
        initWeChatBroadcastReceiver();

        hasTopicData = infoDetailData.hasTopicData();
        if(hasTopicData) {
            topicRefreshView.autoRefresh();
        } else if(getDataUtil.getDetailData()){
            showBgLoadingDialog();
        }
    }

    private void initView(){
        topicRefreshView.setRefreshEnabled(true);
        topicRefreshView.setLoadMoreEnabled(true);
        topicRefreshView.setOnRefreshListener(this);
        topicRefreshView.setOnLoadMoreListener(this);

        topicBottomTalkBar.setContentViewStyle(1);
        topicBottomTalkBar.setShadeView(findViewById(R.id.topic_shade_view));
        topicBottomTalkBar.setTalkBottomBarCallback(this);

        topicDelete.setOnClickListener(this);
        findViewById(R.id.topic_return).setOnClickListener(this);
        findViewById(R.id.topic_praise_btn).setOnClickListener(this);
        findViewById(R.id.topic_reward_btn).setOnClickListener(this);

        topicOtherRv.setHasFixedSize(true);
        topicOtherRv.setLayoutManager(new LinearLayoutManager(this));
        topicOtherRv.setAdapter(infoTopicAdapter);

        deleteDialog = new CommDialog(this);
        deleteDialog.setContent("确定删除该话题？");
        deleteDialog.setLeft("取消");
        deleteDialog.setRight("删除");
        deleteDialog.setRightListener(this);

        updataTopicMainView();
        updataTopicListView();
    }

    private void initWeChatBroadcastReceiver(){
        weChatLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        weChatBroadcaseReciver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                int errorCode = intent.getIntExtra(PayActivity.WECHAT_PAY_ERR_CODE, -1);
                int type = intent.getIntExtra(PayActivity.WECHAT_PAY_TYPE, -1);
                String scoopId = intent.getStringExtra(PayActivity.WECHAT_PAY_SCOOP_ID);
                String userId = intent.getStringExtra(PayActivity.WECHAT_PAY_USER_ID);
                String userName = intent.getStringExtra(PayActivity.WECHAT_PAY_USER_NAME);
                String userIcon = intent.getStringExtra(PayActivity.WECHAT_PAY_USER_ICON);
                TopicInfo topicInfo = infoDetailData.getTopicInfo();
                if(errorCode != BaseResp.ErrCode.ERR_OK
                        || type != infoDetailData.getLinkType()
                        || scoopId == null || !scoopId.equals(topicInfo.getTopicId())
                        || userId == null || userId.equals(topicInfo.getUserId()))
                    return;

            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PayActivity.WECHAT_PAY_SUCCESS);
        weChatLocalBroadcastManager.registerReceiver(weChatBroadcaseReciver, intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updataTopicMainView();
        updataTopicListView();
    }

    @Override
    protected void onDestroy() {
        weChatLocalBroadcastManager.unregisterReceiver(weChatBroadcaseReciver);
        super.onDestroy();
    }

    private void updataTopicMainView(){
        TopicInfo topicInfo = infoDetailData.getTopicInfo();
        if(topicInfo == null || topicInfo.getTopicId() == null      // 显示抢开话题
                || topicInfo.getTopicId().trim().length() == 0){
            topicRemindView.setVisibility(View.VISIBLE);
            topicDataView.setVisibility(View.GONE);
        } else{                                                     // 显示视图
            topicRemindView.setVisibility(View.GONE);
            topicDataView.setVisibility(View.VISIBLE);

            topicCount.setText(topicInfo.getDiscuss() + "家公司讨论过");
            ImageLoadUtil.loadCircle(this,
                    topicInfo.getPortrait() + "?imageView2/2/w/80/interlace/1", topicHead);
            if(topicInfo.getUserName() != null && topicInfo.getUserName().trim().length() > 0) {
                topicName.setVisibility(View.VISIBLE);
                topicName.setText(topicInfo.getUserName());
            } else{
                topicName.setVisibility(View.GONE);
            }
            if(topicInfo.getContent() != null && topicInfo.getContent().trim().length() > 0)
                topicContent.setText(topicInfo.getContent());
            if(topicInfo.getDiscuss() == 1
                    && application.getUserData() != null
                    && application.getUserData().getIsLogin() == 1
                    && topicInfo.getUserId().equals(application.getUserData().getUuid()))
                topicDelete.setVisibility(View.VISIBLE);
            else
                topicDelete.setVisibility(View.GONE);
            topicPraiseNum.setText(topicInfo.getPraiseNum() + "");
            topicRewardNum.setText(0 + "");
        }
    }

    private void updataTopicListView(){
        infoTopicAdapter.updateAdapter(infoDetailData.getTopicList());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topic_return:
                finish();
                break;
            case R.id.topic_delete:
                deleteDialog.show();
                break;
            case R.id.topic_praise_btn:
                topicBottomTalkBar.praise();
                break;
            case R.id.topic_reward_btn:
                topicBottomTalkBar.payReward();
                break;
            case R.id.right_btn:
                deleteTopic();
                break;
        }
    }

    /* 删除话题 */
    private void deleteTopic(){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("topicId", infoDetailData.getTopicInfo().getTopicId());
        HttpHelper.getInstance(this).topicDelete(param, TOPIC_DELETE_CODE, this);
        deleteDialog.cancel();
    }

    @Override
    public void onRefresh() {
        getDataUtil.getTopicList(0);
    }

    @Override
    public void onLoadMore() {
        getDataUtil.getTopicList(1);
    }

    /* 底部栏回调 */
    @Override
    public void viewNeedToUpdate(int requestType, boolean isSuccess) {
        if(!isSuccess)
            return;
        if(requestType == TalkBottomBarView.PRAISE_CODE){
            updataTopicMainView();
        } else if(requestType == TalkBottomBarView.COMMIT_COMMENT_CODE) {
            // 话题提交成功并且是抢开话题，需要重新获取一遍话题数据
            if (infoDetailData.getTopicInfo().getTopicId() == null
                    || infoDetailData.getTopicInfo().getTopicId().trim().length() == 0) {
                updataTopicMainView();
                getDataUtil.getTopicData();
            } else {
                if(infoDetailData.getTopicInfo().getDiscuss() == 1)
                    updataTopicMainView();
                updataTopicListView();
                topicOtherRv.smoothScrollToPosition(0);
            }
        }
    }

    private int isCollection;
    @Override
    public void onStart(int requestType) {
        if(requestType == TOPIC_DELETE_CODE){
            showLoading();
            isCollection = infoDetailData.getTopicInfo().getIsCollection();
        }
    }
    @Override
    public void onCompleted(int requestType) {
        cancleLoading();
        if(requestType == TOPIC_DELETE_CODE){
            ToasUtil.toast(this, "话题删除成功");
        }
    }
    @Override
    public void onError(int requestType) {
        cancleLoading();
        if(requestType == TOPIC_DELETE_CODE){
            ToasUtil.toast(this, "抱歉，话题删除失败，请稍后重试");
        }
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
            return;
        }
        if(requestType == TOPIC_DELETE_CODE){
            infoDetailData.setTopicInfo(new TopicInfo());
            infoDetailData.setTopicList(null);
            infoDetailData.getTopicInfo().setIsCollection(isCollection);
            topicBottomTalkBar.updateView();
            updataTopicMainView();
            updataTopicListView();
            getDataUtil.getTopicData();
        }
    }

    /* 获取数据完成后的回调 */
    @Override
    public void onFinish(int requestCode, boolean isSuccess) {
        if(requestCode == ToutiaoGetDataUtil.GET_TOPIC_DATA){                   // 获取话题数据
            if(isSuccess) {
                topicBottomTalkBar.updateView();
                updataTopicMainView();
                if(!hasTopicData)
                    topicRefreshView.autoRefresh();
                hasTopicData = infoDetailData.hasTopicData();
            } else {
                ToasUtil.toast(this, "抱歉，话题数据获取失败");
            }
            cancleBgLoadingDialog();
        } else if(requestCode == ToutiaoGetDataUtil.GET_TOPIC_LIST_REFRESH){    // 下拉刷新
            topicRefreshView.refreshComplete();
            updataTopicListView();
        } else if(requestCode == ToutiaoGetDataUtil.GET_TOPIC_LIST_LOAD){       // 加载更多
            topicRefreshView.loadMoreComplete();
            updataTopicListView();
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.topic_activity_anim_enter,
                R.anim.topic_activity_anim_exit);
    }
}
